package cc.idoone.spring_boot_hello.shiro.controller;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author hemj
 * @since 2017/10/21
 */
@Controller
@RequestMapping("/shiro")
public class ShiroController {

	@GetMapping("/index")
	public String index() {
		return "shiro/index";
	}

	/**
	 * 登录过程其实只是处理异常的相关信息，具体的登录验证交给 shiro 来处理
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, Map<String, Object> map) throws Exception {
		System.out.println("ShiroController.login()");
		// 登录失败从 request 中获取 shiro 处理的异常信息。
		// shiroLoginFailure: 就是 shiro 异常类的全类名.
		String exception = (String) request.getAttribute("shiroLoginFailure");
		System.out.println("login exception=" + exception);
		String msg = "";
		if (exception != null) {
			if (UnknownAccountException.class.getName().equals(exception)) {
				System.out.println("UnknownAccountException -- > 账号不存在：");
				msg = "UnknownAccountException -- > 账号不存在：";
			} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
				System.out.println("IncorrectCredentialsException -- > 密码不正确：");
				msg = "IncorrectCredentialsException -- > 密码不正确：";
			} else if ("其他自定义异常".equals(exception)) {
				System.out.println("其他自定义异常");
				msg = "其他自定义异常";
			} else {
				msg = "else >> " + exception;
				System.out.println("else -- >" + exception);
			}
		}
		map.put("msg", msg);
		// 此方法不处理登录成功, 由shiro 进行处理
		return "shiro/login";
	}

	@GetMapping("/userInfo")
	public String userInfo() {
		return "shiro/userInfo";
	}

	@GetMapping("/userAdd")
	public String userAdd() {
		return "shiro/userAdd";
	}

	@GetMapping("/userDel")
	@RequiresPermissions("sys.user:userDel") //权限管理
	public String userDel() {
		return "shiro/userDel";
	}

	@RequestMapping("/403")
	public String unauthorized() {
		System.out.println("------没有权限-------");
		return "shiro/403";
	}

}

